package cao.oschina.function.me;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import cao.oschina.R;
import cao.oschina.activity.ToolBarActivity;
import cao.oschina.api.URLs;
import cao.oschina.app.Config;
import cao.oschina.bean.Result;
import cao.oschina.bean.User;
import cao.oschina.util.FileUtils;
import cao.oschina.util.TimeUtil;
import cao.oschina.widget.dialog.AlertDialog;
import hd.util.ToastUtil;
import hd.util.bitmap.BitmapMethod;
import hd.util.file.FileUtil;
import hd.util.http.HttpClient;
import hd.util.http.HttpRequestListener;
import hd.util.http.HttpResponse;
import hd.util.load.ImageLoader;

/**
 * 我的资料
 * <p/>
 * Created by Haidy on 15/4/6.
 */
public class MyInformation extends ToolBarActivity {

    private ImageView headView;
    private TextView userNameView;
    private TextView joinTimeView;
    private TextView fromView;
    private TextView devplatformView;
    private TextView expertiseView;
    private Config config;

    private Bitmap headImage;

    private final String TAKE_PHOTO = "bit_head.jpg";
    private final String HEAD = "head.jpg";
    private AlertDialog dialog;

    /**
     * 初始化界面
     */
    @Override
    protected void initView() {
        configBack();
        setTitle("我的资料");
        setBody(R.layout.my_information_view);
        headView = (ImageView) getBody().findViewById(R.id.icon);
        userNameView = (TextView) getBody().findViewById(R.id.userName);
        joinTimeView = (TextView) getBody().findViewById(R.id.jointime);
        fromView = (TextView) getBody().findViewById(R.id.from);
        devplatformView = (TextView) getBody().findViewById(R.id.devplatform);
        expertiseView = (TextView) getBody().findViewById(R.id.expertise);
        headView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                remindShowUpdatePortrait();
            }
        });
    }

    /**
     * 提醒更新头像
     */
    private void remindShowUpdatePortrait() {
        dialog = new AlertDialog(this);
        dialog.setContent("请选择更新的方式");
        dialog.addAction("取消", 0)
                .addAction("拍照", 1)
                .addAction("相册", 2)
                .setOnActionListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (v.getId()) {
                            case 1: {
                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, getUri(TAKE_PHOTO));
                                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                                startActivityForResult(intent, 1);
                                break;
                            }
                            case 2: {
                                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);// 此段调用系统相册
                                intent.addCategory(Intent.CATEGORY_OPENABLE);
                                intent.setType("image/jpeg");
                                startActivityForResult(intent, 2);
                                break;
                            }
                            default:
                                dialog.dismiss();
                                break;
                        }
                    }
                }).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1://拍照
                if (resultCode == RESULT_OK) {
                    //进行剪裁图片
                    pictureZoom(getUri(TAKE_PHOTO));
                }
                if (dialog != null) {
                    dialog.dismiss();
                }
                break;
            case 2:
                if (resultCode == RESULT_OK) {
                    //进行剪裁图片
                    pictureZoom(data.getData());
                }
                if (dialog != null) {
                    dialog.dismiss();
                }
                break;
            case 3:
                if (resultCode == RESULT_OK) {
                    Bitmap bm = FileUtil.loadBitmap(getUri(HEAD).getPath());
                    if (bm != null) {
                        bm = BitmapMethod.toRoundBitmap(bm);
                        recycleBitmap();
                        headView.setImageBitmap(headImage = bm);
                        uploadHead();
                    }
                }
                break;
        }
    }

    /**
     * 上传头像
     */
    private void uploadHead() {
        HttpClient client = new HttpClient();
        List<FormBodyPart> partList = new ArrayList<>();
        final File file = new File(getUri(HEAD).getPath());
        try {
            partList.add(new FormBodyPart("uid", new StringBody(app.getConfig().getUid())));
            partList.add(new FormBodyPart("portrait", new FileBody(file)));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        client.httpPost(URLs.PORTRAIT_UPDATE, app.getConfig().getCookies(), partList, new HttpRequestListener() {
            @Override
            public void success(HttpResponse response) {
                Result result = Result.parser(response.text);
                ToastUtil.toastShort(result.errorMessage);
                if ("1".equals(result.errorCode)) {
                    String portrait = app.getConfig().getUserInfo().portrait;
                    if (portrait != null) {
                        FileUtils.deleteHeadImage(getBaseContext(), portrait);
                        try {
                            FileUtil.copyFile(file, FileUtils.getHeadImagePath(getBaseContext(), portrait));
                        } catch (IOException ignored) {
                        }
                    }
                }
            }

            @Override
            public void failure(HttpResponse response) {
                ToastUtil.toastShort(response.info);
            }
        });
    }

    /**
     * 剪裁图片
     *
     * @param uri uri
     */
    public void pictureZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("output", getUri(HEAD));
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("scale", true);// 去黑边
        intent.putExtra("scaleUpIfNeeded", true);//
        startActivityForResult(intent, 3);
    }

    /**
     * 获取图片地址
     *
     * @return uri
     */
    private Uri getUri(String name) {
        File file = new File(FileUtil.getSoftRootPath(getBaseContext(), "oschina") + File.separator + name);
        return Uri.fromFile(file);
    }

    /**
     * 初始化数据
     */
    @Override
    protected void initData() {
        config = app.getConfig();
        loadInformation();
    }

    /**
     * 加载用户信息
     */
    private void loadInformation() {
        new HttpClient().httpGet(URLs.MY_INFORMATION + "?uid=" + config.getUid(), config.getCookies(), new HttpRequestListener() {
            @Override
            public void success(HttpResponse response) {
                User user = User.parser(response.text);
                showUserInfo(user);
            }

            @Override
            public void failure(HttpResponse response) {
                ToastUtil.toastShort(response.info);
            }
        });
    }

    /**
     * 显示用户信息
     *
     * @param user user
     */
    private void showUserInfo(User user) {
        userNameView.setText(user.name);
        joinTimeView.setText(TimeUtil.friendTime(user.jointime));
        fromView.setText(user.from);
        devplatformView.setText(user.devplatform);
        expertiseView.setText(user.expertise);
        if (user.portrait != null) {
            ImageLoader.setOnSingleImageLoaderListener(user.portrait, FileUtils.getHeadImagePath(getBaseContext(), user.portrait), new ImageLoader.OnSingleImageLoaderListener() {
                @Override
                public void onLoaded(Bitmap bitmap) {
                    recycleBitmap();
                    if (bitmap != null && !bitmap.isRecycled()) {
                        headView.setImageBitmap(headImage = bitmap);
                    } else {
                        headView.setImageResource(R.mipmap.ic_account_circle_grey600_36dp);
                    }
                }
            });
        } else {
            headView.setImageResource(R.mipmap.ic_account_circle_grey600_36dp);
        }
    }

    /**
     * 回收位图
     */
    private void recycleBitmap() {
        if (headImage != null && !headImage.isRecycled()) {
            headImage.recycle();
        }
    }

    @Override
    protected void onDestroy() {
        recycleBitmap();
        super.onDestroy();
    }
}
